package sg.nus.iss.vmcs.models;

import java.util.Arrays;
import java.util.HashMap;

import sg.nus.iss.vmcs.VMCSException;

/**
 * Registry of coins that are currently accepted by the system. 
 * This also provides the single location where coin samples are obtained
 * @author Raj
 * @author Philip
 */
public class CoinRegistry {
	
	/** Hashmap Containing  */
	private HashMap<Integer,Coin> standardCoins = new HashMap<Integer,Coin>();
	
    /**
     * Creates an instance of Coin Registry.
     * Marked as private for Singleton
     */
    private CoinRegistry(){}
	
    /**
     * Gets an instance of the Coin Registry
     * @return Initialized Coin Registry
     * @throws VMCSException
     */
    public static CoinRegistry getInstance() {
    	CoinRegistry cr = CoinRegistryHolder.getCoinRegistry();    	
    	return cr;
    }
    
    /**
     * Gets a coin from the list of standard coins
     * @param coinValue Value of the coin to get
     * @return Coin object
     */
    public Coin getCoin(int coinValue) {
    	return standardCoins.get(coinValue);
    }
    
    /**
     * Adds a coin to the list of standard coins
     * @param coin the coin to add to the standard coins list
     * @return aCoin object
     */
    public void addCoin(Coin aCoin) {
    	standardCoins.put(aCoin.getValue(), aCoin);
    }
	
    /**
	 * This method will get all coins stored in the registry as a coin array
	 * Updated by Philip - 27/12/2010
	 * @return An Array of coins cointaining all coins in the hashmap
	 */
	public Coin[] getAllCoins() {
		Coin[] coinArray = new Coin[standardCoins.size()];
		standardCoins.values().toArray(coinArray);
		
		Arrays.sort(coinArray, Coin.getCoinComparator());
		return coinArray;
	}

	/**
	 * Holder for the static instance of Coin Registry to avoid synchronization issues 
	 * @author Philip Chew
	 */
	private static class CoinRegistryHolder {
		private static CoinRegistry instance = null;
		
		public static CoinRegistry getCoinRegistry() {
			if(instance  == null) {
				instance = new CoinRegistry();
			}
			
			return instance;
		}
	}
}
